/*******************************************************************************
 * Copyright 2020 huanggefan.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package main

import (
	"context"
	"flag"
	"log"
	"net"
	"net/http"
	"runtime"
	"sync"
	"time"

	"gitee.com/WisdomClassroom/core/models"
	"gorm.io/driver/postgres"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"

	grpcRuntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"

	"gitee.com/WisdomClassroom/chapter/glb"
	"gitee.com/WisdomClassroom/chapter/service"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
)

var (
	BuildTag  string
	BuildGo   string
	BuildTime string
)

func runGateway(wg *sync.WaitGroup) {
	defer wg.Done()

	conn, err := grpc.DialContext(
		context.Background(),
		core.FlagGRPCListen,
		grpc.WithBlock(),
		grpc.WithInsecure(),
	)
	if err != nil {
		log.Fatalln("Failed to dial server: ", err)
	}

	gateway := grpcRuntime.NewServeMux()
	err = pb.RegisterChapterServiceHandler(context.Background(), gateway, conn)
	if err != nil {
		log.Fatalln("Failed to register gateway: ", err)
	}

	gwServer := &http.Server{
		Addr:    core.FlagHttpListen,
		Handler: gateway,
	}

	err = gwServer.ListenAndServe()
	if err != nil {
		glb.Logger.Error(err.Error())
		return
	}
}

func runServer(wg *sync.WaitGroup) {
	defer wg.Done()

	listen, err := net.Listen("tcp", core.FlagGRPCListen)
	if err != nil {
		glb.Logger.Error(err.Error())
		return
	}

	grpcServer := grpc.NewServer()
	pb.RegisterChapterServiceServer(grpcServer, &service.Service{})

	if err = grpcServer.Serve(listen); err != nil {
		glb.Logger.Error(err.Error())
		return
	}
}

func main() {
	core.PublicFlag(BuildTag, BuildGo, BuildTime)
	core.PublicServerFlag()
	flag.Parse()

	if core.FlagHelp {
		flag.Usage()
		return
	}
	if core.FlagVersion {
		core.PublicVersion()
		return
	}
	if !core.FlagUseSqlite && !core.FlagUsePG {
		flag.Usage()
		return
	}

	if core.FlagLogWithUDP {
		addr, err := net.ResolveUDPAddr("udp", core.FlagLogAddr)
		if err != nil {
			log.Fatalln(err)
		}
		glb.Logger, err = core.NewUDPLogger(core.FlagLogLevel, addr, 10240)
		if err != nil {
			log.Fatalln(err)
		}
	} else {
		glb.Logger = core.NewLogger(core.FlagLogLevel)
	}

	if core.FlagPPROFEnable {
		go core.StartPPOFDebug(http.Server{Addr: core.FlagPPROFListen}, true)
		time.Sleep(1 * time.Second)
	}

	config := &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		Logger: logger.New(
			glb.Logger,
			logger.Config{
				LogLevel: core.GetGormLogLevel(),
				Colorful: false,
			},
		),
	}
	var err error
	if core.FlagUseSqlite {
		glb.DB, err = gorm.Open(sqlite.Open(core.FlagSqliteDB), config)
	} else {
		glb.DB, err = gorm.Open(postgres.Open(models.GetPgSQLConf()), config)
	}
	if err != nil {
		log.Fatalln(err)
	}

	glb.Logger.Info("http listen at: http://" + core.FlagHttpListen)
	glb.Logger.Info("grpc listen at: grpc://" + core.FlagGRPCListen)
	if core.FlagLogWithUDP {
		glb.Logger.Info("log to: udp://" + core.FlagLogAddr)
	}

	wg := new(sync.WaitGroup)
	wg.Add(2)
	go runGateway(wg)
	go runServer(wg)
	wg.Wait()
}

func init() {
	runtime.GOMAXPROCS(1)
}
